package org.example.aitest.utils.gen;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtils {
    
    /**
     * 获取汉字首字母
     * @param chinese 中文字符串
     * @return 首字母字符串
     */
    public static String getFirstLetters(String chinese) {
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        
        char[] chars = chinese.toCharArray();
        for (char c : chars) {
            if (c > 128) { // 是汉字
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        pinyin.append(pinyinArray[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyin.append(c); // 非汉字字符原样保留
            }
        }
        return pinyin.toString().toLowerCase()   ;
    }

    public static String sanitizeTableName(String rawName) {
        // 替换所有非法字符为下划线
        String stage1 = rawName.replaceAll("[^a-zA-Z0-9_]", "_");
        //合并连续下划线
        String stage2 = stage1.replaceAll("_+", "_");
        //去除首尾下划线
        String stage3 = stage2.replaceAll("^_|_$", "");
        return stage3.isEmpty() ? "unknown" : stage3;
    }
}